<template>
  <div id="appointmentManageConfig">
    <el-form :model="form" label-width="100px">
      <template v-for="(item,index) in form.data">
        <el-form-item label="预约起止时间" :key="'times'+index">
          <el-time-picker
            v-model="form.data[index].times"
            is-range
            format='HH:mm'
            value-format="HH:mm"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item label="预约人数" :key="'appointmentNum'+index">
          <el-input v-model="form.data[index].appointmentNum" placeholder="请输入预约人数"></el-input>
        </el-form-item>
        <el-button type="danger" icon="el-icon-minus" circle :key="'button'+index" style="width:40px;height:40px;" @click="remove(form.data[index].id,index)"></el-button>
      </template>
    </el-form>
    <div style="text-align:center;">
      <el-button type="success" icon="el-icon-plus" circle style="width:40px;height:40px;" @click="add()"></el-button>
      <el-button type="primary" :loading='btnLoading' @click="submitForm">保 存</el-button>
    </div>
  </div>
</template>

<script>
import { appointmentOperation,appointmentList,deleteTime } from '@/api/adminConfig/appointmentManageConfig'
export default {
 data() {
    return {
      btnLoading:false,
      form:{
        data:[]
      },
    };
  },
  created(){
    //生成假数据
    this.onLoad()
  },
  methods: {
    //移除
    remove(id,index){
      this.$confirm(`是否删除指定数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(typeof(id),'8888')
        if(typeof(id)=='undefined'){
           this.form.data.splice(index,1)
         this.$message({
              type:'success',
              message:'已移除'
            })
        }else{
           let params={
          id
        }
        let res= await deleteTime(params)
          if(res.code=='2000'){
            this.$message({
              type:'success',
              message:'已移除'
            })
            this.onLoad()
          }
            
        }
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '操作已取消'
        });          
      });
    },
    //新增
    add(){
      this.form.data.push({
        times:['',''],
        appointmentNum:''
      })
      this.$message({
        type:'success',
        message:'已添加'
      })
    },
    setForm(n){
      let tmpArr=n.map(el=>{
        return {
          times:[el.appointmentAm,el.appointmentPm],
          appointmentNum:el.appointmentNum,
          id:el.id
        }
      })
      this.form.data=Object.assign(tmpArr,this.form.data)
    },
    onLoad(){
      this.form.data=[]
      appointmentList({}).then(({data})=>{
        this.setForm(data.reverse())
      }).catch(()=>{
        this.$message({
          type:'error',
          message:'加载失败'
        })
      })
    },
    getLabel(key){
      if(key==='times'){
        return '预约起止时间'
      }else if(key==='appointmentNum'){
        return '预约人数'
      }
    },
    //校验
    validateForm(){
      let flag=true
      let errorMessage='校验未通过！'
      let data=[]
      if(!this.form.data.length){
        return {
          valid:false,errorMessage:'不允许为空！'
        }
      }
      //校验已有数组中是否有空数据，允许为空数组
      for(let i=0;i<this.form.data.length;i++){
        let el=this.form.data[i]
        let { times,appointmentNum,id } = el
        if(!times){
          flag=false
          errorMessage='请检查表单是否已全部填写'
          break
        }
        if(appointmentNum){
          data.push({
            appointmentAm:times[0],
            appointmentPm:times[1],
            appointmentNum,
            id
          })
        }else{
          flag=false
          errorMessage='请检查表单是否已全部填写'
          break
        }
      }
      if(!flag){
        return {
          valid:flag,errorMessage
        }
      }
      //校验表格中是否有重复时间段的数据,允许重叠两端时间,例如10:00-11:00,11:00-12:00,不会报错
      {
        let tmpObj={}
        //确定两端数组tmpObj
        for(let i=0;i<data.length;i++){
          let { appointmentAm,appointmentPm } = data[i]
          let timeA=appointmentAm.split(':')[0]
          let timeB=appointmentAm.split(':')[1]
          let timeC=appointmentPm.split(':')[0]
          let timeD=appointmentPm.split(':')[1]
          tmpObj['v'+i]=[(timeA+timeB)-0,(timeC+timeD)-0]
        }
        for(let key in tmpObj){
          if(!flag){
            break
          }
          let val1=tmpObj[key][0]
          let val2=tmpObj[key][1]
          for(let key2 in tmpObj){
            let val=tmpObj[key2]
            if(val1>val[0]&&val1<val[1]){
              flag=false
              break
            }
            if(val2>val[0]&&val2<val[1]){
              flag=false
              break
            }
          }
        }
        if(!flag){
          return {
            valid:flag,errorMessage:'时间冲突'
          }
        }
      }
      //校验表格中是否有重复时间段的数据,不允许重叠任何时间,例如10:00-11:00,11:00-12:00,会校验错误
      // {
      //   let tmpObj={}
      //   for(let i=0;i<data.length;i++){
      //     if(!flag){//说明内层报错了
      //       break
      //     }
      //     let { appointmentAm,appointmentPm } = data[i]
      //     let timeA=appointmentAm.split(':')[0]
      //     let timeB=appointmentAm.split(':')[1]
      //     let timeC=appointmentPm.split(':')[0]
      //     let timeD=appointmentPm.split(':')[1]
      //     let a=timeA-0
      //     let b=timeB-0
      //     let c=timeC-0
      //     let d=timeD-0
      //     if(i===0){
      //       for(let j=a;j<c+1;j++){
      //         tmpObj['h'+j]={}
      //         if(j===a){
      //           for(let k=b;k<60;k++){
      //             tmpObj['h'+j]['m'+k]=true
      //           }
      //         }else if(j===c){
      //           for(let k=0;k<d+1;k++){
      //             tmpObj['h'+j]['m'+k]=true
      //           }
      //         }else{
      //           for(let k=0;k<60;k++){
      //             tmpObj['h'+j]['m'+k]=true
      //           }
      //         }
      //       }
      //     }else{
      //       for(let j=a;j<c+1;j++){
      //         if(!flag){//说明内层报错了
      //           break
      //         }
      //         //有键名则说明必存在选中时间
      //         let isKey=tmpObj.hasOwnProperty('h'+j)
      //         if(!isKey){
      //           tmpObj['h'+j]={}
      //         }
      //         if(j===a){
      //           for(let k=b;k<60;k++){
      //             //如果这个值是true，说明已经有人预约了
      //             if(tmpObj['h'+j]['m'+k]){
      //               flag=false
      //               errorMessage='请检查预约时间是否冲突,冲突起始时间'+`${timeA+':'+timeB}`
      //               break
      //             }else{
      //               tmpObj['h'+j]['m'+k]=true
      //             }
      //           }
      //         }else if(j===c){
      //           for(let k=0;k<d+1;k++){
      //             if(tmpObj['h'+j]['m'+k]){
      //               flag=false
      //               errorMessage='请检查预约时间是否冲突,冲突起始时间'+`${timeA+':'+timeB}`
      //               break
      //             }else{
      //               tmpObj['h'+j]['m'+k]=true
      //             }
      //           }
      //         }else{
      //           for(let k=0;k<60;k++){
      //             if(tmpObj['h'+j]['m'+k]){
      //               flag=false
      //               errorMessage='请检查预约时间是否冲突,冲突起始时间'+`${timeA+':'+timeB}`
      //               break
      //             }else{
      //               tmpObj['h'+j]['m'+k]=true
      //             }
      //           }
      //         }
      //       }
      //     }
      //   }
      //   if(!flag){
      //     return {
      //       valid:flag,errorMessage
      //     }
      //   }
      // }
      //一般来说走到这就算通过了
      return {
        valid:flag,data
      }
    },
    submitForm() {
      this.btnLoading=true
      let { valid,errorMessage='校验不通过',data=[] }=this.validateForm()
      if(valid){
        console.log(data,'9999999999999999999')
        appointmentOperation({list:data}).then(({code,msg})=>{
          if(code==='2000'){
            this.$message({
              type:'success',
              message:'提交成功'
            })
            this.onLoad()
            this.btnLoading=false
          }else{
            this.$message({
              type:'error',
              message:msg
            })
            this.btnLoading=false
          }
        }).catch(err=>{
          console.log(err)
          this.$message({
            type:'error',
            message:'提交失败!'
          })
          this.btnLoading=false
        })
      }else{
        this.$message({
          type:'error',
          message:errorMessage
        })
        this.btnLoading=false
      }
    },
  }
}
</script>

<style lang='scss' scoped>
#appointmentManageConfig{
  .el-form{
    width: 1000px;
    display: grid;
    grid-template-columns:45% 25% 20%;
    column-gap: 5%;
  }
}
</style>